
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import mailutil.GmailUtil;
/**
 * Servlet implementation class CreateHostUser
 */
@WebServlet("/CreateGuestUser")
public class CreateGuestUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Map<String, String> messages = new HashMap<String, String>();   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateGuestUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String email = request.getParameter("email");
		String str      = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		Random random   = new Random();
		  //char randomChar;
		String ActivationKey = "";
		for (int i = 0;i < 15;i++)
		{
			  ActivationKey     += str.charAt(random.nextInt(str.length()));
		}
		  //Session ["rdnCode"] = ActivationKey;
		
		// nhận tham số từ form nhập
		String from = "dungnq01239@fpt.edu.vn";
		String to = email;
		String cc = "";
		String bcc = "";
		String subject = "HomeStay Booking System - New Account Confirmation";
		String body = "\n\n Thank you for registering with our HomeStay Booking System," + 
		              "\n As a registered user here you will find guests looking for accommodation." +
				      "\n To complete the registration process, please click on the following link:" +
		              "\n <a href = 'http://localhost:8080/HBSPROJECT/Activation?username="+name+"&activationkey="+ActivationKey+"'>http://localhost:8080/HBSPROJECT/Activation/"+ name +"/"+ActivationKey+ "</a>" +			 
		              "\n The HomeStay Booking Team" +
		              "<h2>https://www.vnhomestay.net</h2>";
		String attachments = "";
		
		int sexType = Integer.parseInt(request.getParameter("sex"));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date birthdayDate = new Date();
		try {
			birthdayDate = dateFormat.parse(request.getParameter("birthday"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Timestamp birthday = new Timestamp(birthdayDate.getTime());
		String phoneNumber = request.getParameter("phoneNumber");
		String country = request.getParameter("countryName");
		PrintWriter out = response.getWriter();
		guestUser guestUserObj = new guestUser();
		guestUserObj.setAccount(name);
		guestUserObj.setPassword(pwd);
		guestUserObj.setFirstName(firstName);
		guestUserObj.setLastName(lastName);
		guestUserObj.setSexType(sexType);
		guestUserObj.setBirthday(birthday);
		guestUserObj.setPhoneNumber(phoneNumber);
		guestUserObj.setEmailAddress(email);
		guestUserObj.setUserType(1);
		guestUserObj.setIsMailValidated(0);
		guestUserObj.setCountry(country);
		guestUserObj.setActivationKey(ActivationKey);
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	        session.beginTransaction();
	        session.saveOrUpdate(guestUserObj);
	        session.getTransaction().commit();
	        //HibernateUtil.getSessionFactory().close();
	        GmailUtil.send(from, to, cc, bcc, subject, body, attachments);
			request.setAttribute("messages", messages);
			request.getRequestDispatcher("Register.html").forward(request, response);
			} catch(Exception ex){
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
			}
		out.println("<html><head><title>Guest Manager</title></head><body>");
		out.println("<a>Register successfully</a>" + name + birthday);
		out.println("</body></html>");
	}

}
